#include "mycoin.h"
#include<QPushButton>
#include<QPixmap>
#include<QMessageBox>
#include<QTimer>
MyCoin::MyCoin(QString coinImg)
{
    QPixmap pix;
    bool ret = pix.load(coinImg);
    if (!ret) {
        QString str = QString("图片加载fail, %1").arg(coinImg);
        QMessageBox::critical(this, "加载失败", str);
        return;
    }

    this->setFixedSize(pix.width(), pix.height());
    this->setStyleSheet("QPushButton{border:0px;}");
    this->setIcon(pix);
    this->setIconSize(QSize(pix.width(), pix.height()));

    timer1 = new QTimer(this);
    timer2 = new QTimer(this);


    //初始化胜利标识
    this->isWin = false;

    //监听翻金币事件
    connect(timer1, &QTimer::timeout, [=](){
       QPixmap pix;
       QString str = QString(":/res/Coin000%1.png").arg(this->min++);
       pix.load(str);

       this->setFixedSize(pix.width(), pix.height());
       this->setStyleSheet("QPushButton{border:0px;}");
       this->setIcon(pix);
       this->setIconSize(QSize(pix.width(), pix.height()));

       if (this->min > this->max) {
           this->min = 1;
           this->isAnimation = false;
            timer1->stop();
       }
    });

    connect(timer2, &QTimer::timeout, [=](){
       QPixmap pix;
       QString str = QString(":/res/Coin000%1.png").arg(this->max--);
       pix.load(str);

       this->setFixedSize(pix.width(), pix.height());
       this->setStyleSheet("QPushButton{border:0px;}");
       this->setIcon(pix);
       this->setIconSize(QSize(pix.width(), pix.height()));

       if (this->max < this->min) {
           this->max = 8;
           this->isAnimation = false;
            timer2->stop();
       }
    });
}

void MyCoin::changeFlag()
{
    isAnimation = true;
    //变反
    if (this->flag) {
        timer1->start(30);
        this->flag = false;
    } else {
        timer2->start(30);
        this->flag = true;
    }
}

void MyCoin::mousePressEvent(QMouseEvent *e)
{
    if (this->isAnimation || this->isWin) {
        //正在做动画或者已经胜利，不做鼠标响应
        return;
    }

    //交给父类处理
    QPushButton::mousePressEvent(e);
}
